/**
 * 判断是否为数字
 * @param val
 * @returns {boolean}
 */
function isNumber(val) {
    if (val === "") {
        return false;
    }
    if (val.length > 1) {
        if (val.substring(val.length - 1, val.length) === ".") {
            var len = val.split(".").length - 1;
            if (len > 1) {
                return false;
            }
            val = val.substring(0, val.length - 1);
        }
    }

    var regPos = /^\d+(\.\d+)?$/;
    var regNeg = /^((([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/;
    return regPos.test(val) || regNeg.test(val);

}

/**
 * 获取公共URL
 * @returns {string}
 */
function getCommonUrl() {
    return "http://127.0.0.1:8081/";
}

/**
 * 传入URL跳转新页面
 * @param url
 */
function goToUrl(url) {
    window.location.href = getCommonUrl() + url;
}

function sendGet(url, param, isToken) {
    if (param !== null && param !== undefined && param !== "" && typeof param !== "undefined" && Object.keys(param).length > 0) {
        url = url + "?" + jsonToQueryString(param);
    }
    return sendRequest(url, null, "GET", isToken, true);
}

function sendGetSync(url, param, isToken) {
    if (param !== null && param !== undefined && param !== "" && typeof param !== "undefined" && Object.keys(param).length > 0) {
        url = url + "?" + jsonToQueryString(param);
    }
    return sendRequest(url, null, "GET", isToken, false);
}

function sendPost(url, param, data, isToken) {
    if (param !== null && param !== undefined && param !== "" && typeof param !== "undefined" && Object.keys(param).length > 0) {
        url = url + "?" + jsonToQueryString(param);
    }
    return sendRequest(url, JSON.stringify(data), "POST", isToken, true);
}

function sendPostSync(url, param, data, isToken) {
    if (param !== null && param !== undefined && param !== "" && typeof param !== "undefined" && Object.keys(param).length > 0) {
        url = url + "?" + jsonToQueryString(param);
    }
    return sendRequest(url, JSON.stringify(data), "POST", isToken, false);
}

function sendRequest(url, sendData, method, isToken, isAsync) {
    return new Promise((resolve, reject) => {
        try {
            let result = "";
            let xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange = function () {
                if (xmlhttp.status === 200 || xmlhttp.status === 0) {
                    result = xmlhttp.responseText;
                    if ("" !== result) {
                        resolve({status: xmlhttp.status, result});
                    }
                } else if (xmlhttp.status === 400) {
                    console.warn("Bad Request(parameter is not json format)");
                    reject({status: xmlhttp.status, result});
                } else if (xmlhttp.status === 500) {
                    console.warn("Bad Request(parameter is not json array)");
                    reject({status: xmlhttp.status, result});
                } else {
                    reject({status: xmlhttp.status, result});
                }
            };
            xmlhttp.open(method, url, isAsync);
            xmlhttp.setRequestHeader("Content-type", "application/json");
            xmlhttp.setRequestHeader('tenantId', localStorage.getItem(localStorage.getItem('userId') + ':tenantId'));
            if (isToken) {
                xmlhttp.setRequestHeader('Authorization', 'Bearer ' + localStorage.getItem(localStorage.getItem('userId') + ':token'));
            }
            xmlhttp.send(sendData);
        } catch (e) {
            reject(e);
        }
    });
}

function jsonToQueryString(json) {
    return Object.keys(json)
        .map(key => encodeURIComponent(key) + '=' + encodeURIComponent(json[key]))
        .join('&');
}

/**
 * 列表数据转树状
 * @param list
 * @param idField
 * @param parentField
 * @param childrenField
 * @returns {Array}
 */
// 列表转树状结构
function listToTree(list, idField, parentField, childrenField) {
    var data = [];
    var map = {};
    for (let i = 0; i < list.length; i++) {
        var item = list[i];
        item[childrenField] = [];
        map[item[idField]] = item;
    }
    for (let i = 0; i < list.length; i++) {
        var item = list[i];
        var parentId = item[parentField];
        if (parentId === '0' || map[parentId] == null) {
            data.push(item)
        } else {
            var parentItem = map[parentId];
            var children = parentItem[childrenField]
            children.push(item);
            parentItem[childrenField] = children;
        }
    }
    return data;
}

/**
 * 日期转换
 */
function parseTime(time, pattern) {
    if (arguments.length === 0 || !time) {
        return null;
    }
    const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
    let date;
    if (typeof time === 'object') {
        date = time;
    } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
            time = parseInt(time);
        } else if (typeof time === 'string') {
            time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
            time = time * 1000;
        }
        date = new Date(time)
    }
    const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
    };
    const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key]
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') {
            return ['日', '一', '二', '三', '四', '五', '六'][value]
        }
        if (result.length > 0 && value < 10) {
            value = '0' + value
        }
        return value || 0
    })
    return time_str;
}


/**
 * 动态加载js文件
 * @param {*} srcUrl 文件地址
 * @returns Promise
 */
function loadJs(srcUrl) {
    return new Promise((resolve, reject) => {
        // 判断当前js是否已经加载过
        const scriptNodes = [].slice.call(document.querySelectorAll('script')).map(item => item.src)
        if (scriptNodes.includes(srcUrl)) return resolve()

        const script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = srcUrl
        document.body.appendChild(script)
        script.onload = () => {
            resolve()
        }
        script.onerror = (err) => {
            reject(err)
        }
    })
}

function getDict(param) {
    if (param !== null && param !== undefined && param !== "" && typeof param !== "undefined" && Object.keys(param).length > 0) {
        url = url + "?" + jsonToQueryString(param);
    }
    var promise = sendRequest(url, null, "GET", true, false);
    var result = [];
    promise.then((res) => {
        if (res.status === 200) {
            var jsonData = JSON.parse(res.result);
            result = jsonData.data;
            return result;
        } else {
            return [];
        }
    });
    if (result !== null && result !== undefined && result !== "" && typeof result !== "undefined" && Object.keys(result).length > 0){
        return result;
    }
    return result;
}